{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "1.1 迭代器 不写只用\n",
    "\t任务：展示列表中的数据\n",
    "\t· while+索引+计数器\n",
    "\t· 帮助你对某种对象(str/list/tuple/dict/set)[序列]中的元素进行逐一获取\n",
    "\t\t列表转换成迭代器 \n",
    "\t\t\tv1=iter([11,22,33,44])\n",
    "\t\t\tv1 = [11,22,33,44].__iter__()\n",
    "\t\t获取每个值：反复调用val = v1.__next__()\n",
    "\t\t直到报错：StopIteration表示迭代完毕\n",
    "\t\t判别一个对象是否是迭代器：内部是否有__next__方法 \n",
    "\t\n",
    "\tfor 循环\n",
    "\t1.内部会将v1转换成迭代器\n",
    "\t2.内部反复执行 迭代器.__next__()\n",
    "\t3.取完不报错"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "1.3 生成器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#生成器\n",
    "def func():\n",
    "    print('f1')\n",
    "    yield 1\n",
    "    print('f2')\n",
    "    yield 2\n",
    "    print('f3')\n",
    "    yield 100\n",
    "    print('f4')\n",
    "#函数内部代码不会执行 返回一个生成器对象\n",
    "v1 = func()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "f1\n",
      "1\n",
      "f2\n",
      "2\n",
      "f3\n",
      "100\n",
      "f4\n"
     ]
    }
   ],
   "source": [
    "#生成器可以被for循环，一旦开始循环函数内部代码就会开始执行\n",
    "for item in v1:\n",
    "    print(item)\n",
    "#遇到 yield会终止本次循环"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "总结：函数中如果存在yield，name该函数就是一个生成器函数，调用生成器函数会返回一个生成器，只有被for循环时，生成器内部的代码才会执行，每次循环都会获取yield返回值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def func():\n",
    "    return 11\n",
    "    yield 1\n",
    "    yield 12\n",
    "v = func()\n",
    "for item in v:\n",
    "    print(item)\n",
    "#到return时终止执行 无任何结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#生成器应用\n",
    "while True:\n",
    "    f = open('db','r',encoding='utf-8')\n",
    "    data_list=[]\n",
    "    for i in range(10):\n",
    "        data_list.append(f.readline())\n",
    "    \n",
    "    f.close() #关闭连接\n",
    "    \n",
    "    for row in data_list:\n",
    "        yield row"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
